#!/usr/bin/perl
$\=$/;
use lib 'mods';
use db_config;
use ExploitFarm_SQL;
use Util::Logger;
require 'config.pl';


our $dir='/home/exploit-farm/4flags';
our $ok_dir='ok';
our $ok_str='\+OK\+';
#our $flag_regex='.{38}==';
#MTNzEwECA+hWjCb8t8/FgbEg/mSm1hbU231kjg==

sub parse_file
{
    my $file=shift;

    print "Parsing file: $file";

    open F,$file or warn "Can't open file '$file' : $!";
    seek F, -1, 2;
    my $p = tell F;
    seek F, 0, 0;
    read F , $_ , $p or warn "Can't read from file '$file' : $!";
    close F;
    
    s/[\r\n]//g;
    
    my @flags;
    push (@flags,$1) while(/($flag_regex)/gc);
    local $"="\n";
    print "Flags:\n@flags";
    $db->put_flags('FILE','127.0.0.1',\@flags);
    
    return 1 if (/$ok_str\W*$/c);
    return undef;
}

sub main
{
    opendir D,$dir or die "Can't open dir! : $!";
    opendir O,"$dir/$ok_dir" or die "Can't open dir! : $!";
    closedir O;



    while(my $d = readdir D)
    {
	next if ($d =~ /^(?:\.)|(?:$ok_dir$)/);
	if(parse_file("$dir/$d"))
	{
	    rename("$dir/$d","$dir/$ok_dir/$d") or warn "Error while moving parsed file '$d' : $!";
	}
    }
    closedir D;
}

our $db=new ExploitFarm_SQL($db_host,$db_port,$db_name,$db_login,$db_pass);
$db->connect();
while (1)
{
    main();
    sleep(1);
    #select undef,undef,undef,0.5;
}